<template>
  <view class="shopCar">
    <scroll-view class="product-list" scroll-y :style="{ height: mainHeight }">
      <view class="cart-select">
        <template>
          <view class="selectLeft">
            <view
              :class="selectedAll ? 'selected' : ''"
              @click="handleTrigerSelectAll"
            >
              <uni-icons
                v-if="selectedAll"
                class="selected-icon"
                type="checkbox-filled"
                color="#ff4254"
                size="20"
              ></uni-icons>
              <uni-icons
                v-else
                type="circle"
                color="#aaaaaa"
                size="20"
              ></uni-icons>
            </view>
            <view class="all" @click="handleTrigerSelectAll">全选</view>
            <view class="unite">
              （已选 <span class="span">{{ amount }}</span
              >件，共{{ selectedPrice.toFixed(2) }}元）
            </view>
          </view>
          <view class="clearCart" @click="clearCart">清空购物车</view>
        </template>
      </view>
      <view style="width: 100%" v-if="productList.length > 0">
        <view
          class="shop-cart"
          v-for="(item, index) in productList"
          :key="index"
        >
          <view class="shop-info">
            <view
              @click="handleTriggerSelect(index)"
              :class="item.selectKey ? 'selected' : ''"
            >
              <uni-icons
                class="selected-icon"
                v-if="item.selectKey"
                type="checkbox-filled"
                color="#ff4254"
                size="20"
              ></uni-icons>
              <uni-icons
                v-else
                type="circle"
                color="#aaaaaa"
                size="20"
              ></uni-icons>
            </view>
            <image
              mode="aspectFill"
              class="shop-image"
              :src="baseImgUrl + item.goodImg"
              @click="handleToDetail(item.productId)"
            >
            </image>
          </view>
          <view class="basic">
            <view class="shop-name" @click="handleToDetail(item.productId)">{{
              item.goodName
            }}</view>
            <view class="tag-list">
              规格：<view>{{ item.goodSpecs || "无规格" }}</view>
            </view>
            <view class="basic-footer">
              <view class="price-content">
                <view class="unit">￥</view>
                <view class="price">{{ item.retailPrice }}</view>
              </view>
              <view class="cart-num">
                <view
                  class="symbol"
                  @click.stop="handleOperateCount('del', item, index)"
                  >–</view
                >
                <view class="count">
                  {{ item.cartNum }}
                </view>
                <view
                  class="add"
                  @click.stop="handleOperateCount('add', item, index)"
                  >+</view
                >
              </view>
            </view>
          </view>
        </view>
        <view class="last-child"></view>
      </view>
      <Empty v-else />
      <template v-if="recommend.length > 0">
        <view class="divider">
          <view class="dividerLine"></view>
          <view class="dividerText"
            >为您 <text style="color: #ff4254">♥</text> 推荐</view
          >
          <view class="dividerLine"></view>
        </view>
        <view class="scrollView">
          <view class="recommend">
            <view
              v-for="(item, index) in recommend"
              :key="index"
              class="recommendi"
              @click="handleToDetail(item.id)"
            >
              <view class="image">
                <image :src="baseImgUrl + item.goodImg" mode=""></image>
              </view>
              <view class="name">{{ item.goodName }}</view>
              <view class="leftRight">
                <view class="left">
                  <view class="introduce">
                    <view>规格：{{ item.goodSpecs || "无规格" }}</view>
                    <view>销量：{{ item.virtualSales || 0 }}</view>
                  </view>
                  <view class="price">
                    {{ "￥" + item.retailPrice }}
                  </view>
                </view>
                <view class="right" @click.stop="addShoppingCart(item)">
                  <u-icon
                    name="shopping-cart-fill"
                    color="#fff"
                    size="15"
                  ></u-icon>
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>
    </scroll-view>
    <view class="cart-footer">
      <view class="cart-button">
        <view class="price-content">
          <image src="../static/images/detail/shopCar.png" mode=""></image>
          <view class="unit">￥</view>
          <view class="price">{{ selectedPrice.toFixed(2) }}</view>
        </view>
        <view class="cart-submit" @click="handleSubmit">结算</view>
      </view>
    </view>
  </view>
</template>

<script>
import shoppingCartApi from "@/api/shoppingCart";
import homeApi from "@/api/homePage";
import { getToken } from "@/utils/auth";
import { baseImgUrl } from "@/config";

export default {
  data() {
    return {
      baseImgUrl,
      productList: [],
      selectedAll: false,
      selectedPrice: 0,
      amount: 0,
      selectCartList: [],
      mainHeight: "90%",
      recommend: [],
      modalShow: false, // 防止modal弹出时触发watch
    };
  },
  watch: {
    selectCartList: {
      handler() {
        this.calculatePrice();
      },
      deep: true,
    },
  },
  onLoad() {
    // this.mainHeight = this.$store.getters.heightData.noTabMainHeight
  },
  onShow() {
    const token = getToken();
    // if (!token) {
    //   uni.navigateTo({
    //     url: "/pages/login",
    //   });
    //   return;
    // }
    if (token) {
		this.getUserCart();
		this.getReferralsGoodList();
		}

  },
  methods: {
    // 获取购物车商品
    getUserCart() {
      shoppingCartApi.getUserCart().then((res) => {
        if (res.code == 200) {
          let cartProduct = uni.getStorageSync("cartProduct") || [];
          this.selectCartList = cartProduct || [];
          if (!cartProduct || cartProduct.length <= 0) {
            this.productList = res.rows.map((item) => {
              return { ...item, selectKey: false };
            });
          } else {
            let idsMap = {};
            cartProduct.forEach((item) => {
              idsMap[item.id] = item.selectKey;
            });
            this.productList = res.rows.map((item) => {
              return {
                ...item,
                selectKey: idsMap.hasOwnProperty(item.id)
                  ? idsMap[item.id]
                  : false,
              };
            });
          }
        }
      });
    },
    // 获取推荐商品
    getReferralsGoodList() {
      homeApi.getReferralsGoodList().then((res) => {
        if (res.code == 200) {
          this.recommend = res.data;
        }
      });
    },
    // 加入购物车
    addShoppingCart(item) {
      const token = getToken();
      if (!token) {
        uni.navigateTo({
          url: "/pages/login",
        });
      } else {
        // if (item.ifPurchase) {
        //   uni.showToast({
        //     title: "该礼包已购买",
        //     icon: "none",
        //   });
        //   return;
        // }
        let data = {
          productId: item.id,
          cartNum: 1,
        };
        shoppingCartApi.addShoppingCart(data).then((res) => {
          if (res.code == 200) {
            uni.showToast({
              title: "加购成功！",
              icon: "none",
            });
            this.getUserCart();
          }
        });
      }
    },
    clearCart() {
      this.modalShow = true;
      if (this.productList.length <= 0) {
        uni.showToast({
          title: "购物车没有商品哦！",
          icon: "none",
          mask: true,
        });
      } else {
        uni.showModal({
          title: "提示",
          content: `确认删除${this.productList.length}个商品吗？`,
          cancelText: "取消",
          confirmText: "确定",
          success: (modalRes) => {
            if (modalRes.confirm) {
              this.productList = [];
              this.amount = 0;
              this.selectedPrice = 0;
              this.selectedAll = false;
              this.selectCartList = [];
              uni.removeStorageSync("cartProduct");
              shoppingCartApi.clearCart().then((res) => {
                if (res.code == 200) {
                  uni.showToast({
                    title: "删除成功！",
                    icon: "none",
                    mask: true,
                  });
                  this.modalShow = false;
                }
              });
            }
          },
        });
      }
    },
    handleOperateCount(type, item, index) {
      if (type == "add") {
        shoppingCartApi
          .plusProductNum({
            id: item.id,
            productId: item.productId,
          })
          .then((res) => {
            if (res.code == 200) {
              this.productList[index].cartNum += 1;
            }
          });
      } else {
        if (this.productList[index].cartNum <= 1) {
          uni.showModal({
            title: "提示",
            content: "确认删除该商品吗？",
            cancelText: "取消",
            confirmText: "确定",
            success: (modalRes) => {
              if (modalRes.confirm) {
                shoppingCartApi.delCartProduct({ id: item.id }).then((res) => {
                  if (res.code == 200) {
                    uni.removeStorageSync("cartProduct");
                    uni.showToast({
                      title: "删除成功！",
                      icon: "none",
                      mask: true,
                    });
                    this.getUserCart();
                  }
                });
              }
            },
          });
        } else {
          shoppingCartApi
            .reduceProductNum({
              id: item.id,
              productId: item.productId,
            })
            .then((res) => {
              if (res.code == 200) {
                this.productList[index].cartNum -= 1;
              }
            });
        }
      }
      this.selectCartList = this.productList.filter((el) => el.selectKey);
    },
    handleTriggerSelect(index) {
      this.$set(this.productList, index, {
        ...this.productList[index],
        selectKey: !this.productList[index].selectKey,
      });
      this.selectCartList = this.productList.filter((el) => el.selectKey);
    },
    handleTrigerSelectAll() {
      this.selectedAll = !this.selectedAll;
      if (this.selectedAll) {
        this.productList.map((el) => {
          el.selectKey = true;
        });
        this.selectCartList = this.productList;
      } else {
        this.productList.map((el) => {
          el.selectKey = false;
        });
        this.selectCartList = [];
      }
    },
    handleToDetail(id) {
      uni.navigateTo({
        url: `/subPages/details/goodDetail?id=${id}`,
      });
    },
    toProductList() {
      uni.switchTab({
        url: "/pages/store2",
      });
    },
    handleSubmit() {
      if (this.selectCartList.length <= 0) {
        uni.showToast({
          title: "请选择商品",
          icon: "none",
        });
        return;
      }
      uni.setStorageSync("cartProduct", this.selectCartList);
      uni.navigateTo({
        url: "/subPages/details/confirmOrder?source=cart",
      });
    },
    calculatePrice() {
      if (this.modalShow) return;
      const len = this.productList.length;
      this.selectedPrice = this.selectCartList.reduce((retailPrice, item) => {
        return retailPrice + item.cartNum * item.retailPrice;
      }, 0);
      this.amount = this.selectCartList.reduce((retailPrice, item) => {
        return retailPrice + item.cartNum;
      }, 0);
      this.selectedAll =
        len &&
        len === this.selectCartList.length &&
        this.selectCartList.length > 0;
    },
  },
};
</script>

<style lang="scss" scoped>
.shopCar {
  width: 100%;
  height: 100%;
  background-color: #fff;
}

.product-list {
  height: 60vh;
}

page {
  background: rgb(246, 246, 246);
  padding-bottom: 150rpx;
}

.last-child {
  height: 80upx;
}

.checkbox {
  display: flex;
  justify-items: center;
  align-items: center;
  width: 28px;
  height: 28px;
  border: 2rpx solid rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  margin: 0 24rpx 0 8rpx;

  &.selected {
    // padding: 2rpx;
    border: none;
    // background: linear-gradient(to right, #FEEF3C, #F3CD34);

    .selected-icon {
      margin: 2rpx;
      color: #fff !important;
    }
  }
}

.shop-cart {
  width: 95%;
  background: #fff;
  margin: 16rpx;
  padding: 16rpx 0;
  box-sizing: border-box;
  border-radius: 16rpx;
  display: flex;
  position: relative;

  .delete-icon {
    position: absolute;
    top: -12rpx;
    right: -12rpx;
    color: #df3e36 !important;
  }

  .shop-info {
    display: flex;
    align-items: center;

    .shop-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 12rpx;
      margin: 0 15rpx;
    }
  }

  .basic {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 0 16rpx;

    .shop-name {
      font-size: 30rpx;
      color: #000;
      font-weight: 600;
    }

    .tag-list {
      // flex: 1;
      // margin-top: 8rpx;
      display: flex;
      color: #727272;
      align-items: center;
      font-size: 26rpx;
    }

    .basic-footer {
      display: flex;
      justify-content: space-between;

      .cart-num {
        display: flex;
        font-size: 28rpx;

        .count {
          width: 80rpx;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
        }

        .symbol {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40rpx;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
          border: 1px solid #000;
          color: #000;
          border-radius: 15rpx;
        }

        .add {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40rpx;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
          border: 1rpx solid #000;
          color: #fff;
          background-color: #000;
          border-radius: 15rpx;
        }
      }

      .price-content {
        display: flex;
        align-items: center;
        color: #000;
        font-weight: 600;
        font-size: 28rpx;
      }
    }
  }
}

.divider {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .dividerText {
    letter-spacing: 2px;
    padding: 0 5%;
  }

  .dividerLine {
    border-bottom: 1px solid #cac5c5;
    width: 28%;
  }
}

.scrollView {
  width: 100%;
  padding: 0 4%;
  box-sizing: border-box;

  // height: 100%;
  .recommend {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .recommendi {
    width: 48%;
    margin: 20rpx 0;
    position: relative;

    .hearts {
      position: absolute;
      top: 40rpx;
      right: 40rpx;
      width: 60rpx;
      height: 60rpx;
    }

    .heart {
      background: url("../static/images/home/heart.png") no-repeat;
      background-size: 100%;
    }

    .heartActive {
      background: url("../static/images/home/heart_active.png") no-repeat;
      background-size: 100%;
    }

    .image {
      width: 100%;
      height: 335rpx;

      image {
        width: 100%;
        height: 100%;
        border-radius: 8%;
      }
    }

    .name {
      width: 100%;
      font-size: 28rpx;
      line-height: 55rpx;
      font-weight: 600;
    }

    .leftRight {
      display: flex;
      position: relative;

      .left {
        width: calc(100% - 20rpx);

        .text {
          color: #858585;
        }

        .introduce {
          width: 100%;
          font-size: 26rpx;
        }

        .price {
          width: 100%;
          height: 60rpx;
          font-size: 35rpx;
          line-height: 60rpx;
          font-weight: 600;
        }

        .VipPrice {
          width: 180rpx;
          height: 40rpx;
          background-color: #fee6c3;
          border-radius: 3px;
          display: flex;

          .vip {
            width: 50%;
            height: 100%;
            background: url("../static/images/home/vip.png") no-repeat;
            background-size: 100% 100%;
            display: initial-block;
          }

          span {
            text-align: center;
          }
        }
      }

      .right {
        position: absolute;
        width: 20px;
        height: 20px;
        background-color: #ff4254;
        border-radius: 3px;
        bottom: 0;
        right: 2px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.cart-select {
  width: 100%;
  padding: 25rpx 15rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  letter-spacing: 1rpx;

  .selectLeft {
    width: 70%;
    display: flex;
    align-items: center;
  }

  .all {
    margin-left: 15rpx;
    color: #000;
    font-weight: 600;
  }

  .unite {
    font-size: 26rpx;
    color: #727272;

    .span {
      margin-left: 8rpx;
    }
  }

  .clearCart {
    color: #ff4254;
    font-size: 26rpx;
  }
}

.cart-footer {
  position: fixed;
  bottom: 0;
  background: #fff;
  width: 702rpx;
  padding: 24rpx;
  box-sizing: border-box;
  left: 24rpx;
  display: flex;
  justify-content: space-between;
  border-top: 1rpx solid #dddddd;

  .cart-button {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .price-content {
      display: flex;
      align-items: flex-end;
      color: #000;

      .unit {
        font-size: 24rpx;
      }

      image {
        width: 75rpx;
        height: 75rpx;
        margin-right: 15rpx;
      }

      .price {
        font-size: 38rpx;
      }
    }

    .cart-submit {
      margin-left: 24rpx;
      background: #000;
      border-radius: 60rpx;
      height: 90rpx;
      width: 330rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #ffffff;
    }
  }
}
</style>
